
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.serializers.sku_serializers import *
from meiduo_admin.paginators import MyPage



# 获取可选规格信息
class SpecOptView(ListAPIView):
    queryset = SPUSpecification.objects.all()
    serializer_class = SpecModelSerializer

    pagination_class = None

    def get_queryset(self):
        # 根据路径中的spu主键值，过滤出关联的规格查询集
        # 问题点：如何在非视图函数中获取路径关键字参数
        # 答：self.kwargs是一个字典保存路径关键字参数
        spu_id = self.kwargs.get('pk')
        return self.queryset.filter(spu_id=spu_id)


# 获取可选SPU列表数据
class SPUSimpleView(ListAPIView):
    queryset = SPU.objects.all()
    serializer_class = SPUSimpleModelSerializer

    pagination_class = None

# 获取分类列表数据
class SKUCateView(ListAPIView):
    queryset = GoodsCategory.objects.all()
    serializer_class = GoodsCateModelSerializer

    # 如果类属性pagination_class设置为None。表示当前视图取消分页
    pagination_class = None

    def get_queryset(self):
        # 过滤三级分类对象查询集
        return self.queryset.filter(parent_id__gt=37)


# SKU视图集
class SKUGoodsView(ModelViewSet):
    queryset = SKU.objects.all()
    serializer_class = SKUModelSerializer

    pagination_class = MyPage

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            return self.queryset.filter(name__contains=keyword)
        return self.queryset.all()

